import os
import json
import time
from flask import session, redirect, url_for, request
from utils.user_management_utils import get_user_manager

class AuthManager:
    def __init__(self):
        self.user_manager = get_user_manager()
        # 设置会话过期时间（秒），默认为24小时
        self.session_timeout = 24 * 60 * 60
    
    def login(self, username, password):
        """用户登录"""
        if self.user_manager.verify_password(username, password):
            # 更新用户最后登录时间
            self.user_manager.update_last_login(username)
            
            # 获取用户信息
            user_info = self.user_manager.get_user(username)
            
            # 设置会话
            session['username'] = username
            session['role'] = user_info['role']
            session['login_time'] = time.time()
            
            # 检查是否需要重置密码
            if user_info.get('password_reset_required', False):
                session['password_reset_required'] = True
                return True, "需要重置密码"
            
            return True, "登录成功"
        else:
            return False, "用户名或密码错误"
    
    def logout(self):
        """用户登出"""
        session.clear()
        return True, "退出成功"
    
    def change_password(self, username, old_password, new_password):
        """修改密码"""
        # 验证旧密码
        if not self.user_manager.verify_password(username, old_password):
            return False, "旧密码错误"
        
        # 更新密码
        result, message = self.user_manager.update_user(username, new_password=new_password)
        if result:
            # 清除密码重置标志
            if 'password_reset_required' in session:
                del session['password_reset_required']
            
            # 强制用户重新登录
            session.clear()
        return result, message
    
    def is_authenticated(self):
        """检查用户是否已认证"""
        if 'username' not in session:
            return False
        
        # 检查会话是否过期
        if time.time() - session['login_time'] > self.session_timeout:
            self.logout()
            return False
        
        # 刷新会话时间
        session['login_time'] = time.time()
        return True
    
    def get_current_user(self):
        """获取当前登录用户信息"""
        if self.is_authenticated():
            username = session['username']
            return self.user_manager.get_user(username)
        return None
    
    def check_permission(self, required_permission):
        """检查用户是否有指定权限"""
        if not self.is_authenticated():
            return False
        
        username = session['username']
        return self.user_manager.check_permission(username, required_permission)
    
    def permission_required(self, required_permission):
        """权限装饰器，与app.py中的权限控制保持一致"""
        from functools import wraps
        def decorator(f):
            @wraps(f)
            def wrapped_function(*args, **kwargs):
                if not self.is_authenticated():
                    return redirect(url_for('login'))
                
                # 检查用户是否存在
                # 这可以解决容器重新部署后cookie保留的问题
                username = session.get('username')
                if username and not self.user_manager.get_user(username):
                    # 用户不存在，清除会话
                    session.clear()
                    return redirect(url_for('login'))
                
                if not self.check_permission(required_permission):
                    return "无权限访问此页面", 403
                
                return f(*args, **kwargs)
            return wrapped_function
        return decorator

# 创建单例实例
_auth_manager = None
def get_auth_manager():
    """获取认证管理器单例"""
    global _auth_manager
    if _auth_manager is None:
        _auth_manager = AuthManager()
    return _auth_manager